<?php
/**** 5/27/10 Element.php v2.3 ****/

class Element {
	protected $tag;
	public $contents;
	public $attributes;
	
	public function __construct($tag, $content = NULL, Array $attributes = NULL) {
		$this->tag = $tag;
		$this->contents = $content;
		$this->attributes = $attributes;
	}
	
	public function __toString() {
		$attributes = '';
		$c = NULL;
		if($this->attributes) {
			if(is_array($this->attributes)) {
				foreach($this->attributes as $attr => $value) {
					$attributes .= " $attr=\"$value\"";
				}
			}
			else {
				return '';
			}
		}
		if($this->contents == NULL) {
			return "<$this->tag$attributes />";
		}
		else {
			if(is_array($this->contents)) {
				foreach($this->contents as $item) {
					$c .= ($item instanceof Element) ? $item : htmlspecialchars($item);
				}
			}
			else {
				$c = ($this->contents instanceof Element) ? $this->contents : htmlspecialchars($this->contents);
			}
			return "<$this->tag$attributes>$c</$this->tag>";
		}
	}
	
	public function appendTo(Element $parent) {
		$parent->contents .= (string)$this;
		return $this;
	}
}

?>